package com.wwwarehouse.contract.orders.place_order;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.animation.Animation;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.base.BaseApplication;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.keyboard.VirtualKeyboardView;
import com.wwwarehouse.common.custom_widget.time_pick.ChoosePickerDialog;
import com.wwwarehouse.common.tools.ImageloaderUtils;
import com.wwwarehouse.common.tools.rsa.StringUtils;
import com.wwwarehouse.contract.adapter.OrderDetailAdapter;
import com.wwwarehouse.contract.adapter.PlaceOrdersBrowseGoodsDetailsRecycleAdapter;
import com.wwwarehouse.contract.bean.OrderDetailListBean;
import com.wwwarehouse.contract.bean.PlaceOrdersBrowseGoodsBean;
import com.wwwarehouse.contract.bean.ShopingCarTotalPriceBean;
import com.wwwarehouse.contract.contract.TheParentFragment;
import com.wwwarehouse.contract.core.BindEventBus;
import com.wwwarehouse.contract.core.ContractConstant;
import com.wwwarehouse.contract.event.OrderDetailOnItemClickEvent;
import com.wwwarehouse.contract.event.RefreshShoppCardEvent;
import com.wwwarehouse.contract.event.ShoppingCarQtyEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import contract.wwwarehouse.com.contract.R;
import de.greenrobot.event.EventBus;

/**
 * Created by feng.gao on 2017/10/18.
 */
public class OrderDetailFragment extends TheParentFragment {
	private List<OrderDetailListBean.OrderDetailBean> list = new ArrayList<>();
	private ListView myListView;
	private OrderDetailAdapter orderDetailAdapter;
	private ImageView mLogoIv;
	private TextView mNameTv;
	private TextView mTotalPriceTv;
	private List<String> times = new ArrayList<>();
	private List<String> payways = new ArrayList<>();
	private String supplierBusinessId;
	private String mDemanId;
	private PopupWindow popupWindow;
	private int shoppingNum;
	private boolean isMeasured = false;

	@Override
	protected int getContentId() {
		return R.layout.contract_order_detail_listview_layout;
	}

	@Override
	protected void init(View view) {
		myListView = (ListView) view.findViewById(R.id.order_detail_lv);
		mLogoIv = (ImageView) view.findViewById(R.id.logo_iv);
		mNameTv = (TextView) view.findViewById(R.id.name_tv);
		view.findViewById(R.id.top_layout).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				EventBus.getDefault().post(new OrderDetailOnItemClickEvent());
			}
		});
		mTotalPriceTv = (TextView) view.findViewById(R.id.total_price_tv);
		myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				EventBus.getDefault().post(new OrderDetailOnItemClickEvent());
			}
		});
		myListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
				EventBus.getDefault().post(new OrderDetailOnItemClickEvent());
				times.clear();
				payways.clear();
				if (list.size() > 0 && list.get(position).getPayment() != null) {
					if (StringUtils.isNoneNullString(list.get(position).getPayment().getPayMonth()) && !(list.get(position).getPayment().getPayMonth().equals("0"))) {
						times.add("每月" +list.get(position).getPayment().getPayMonth() + "日付");
					}
					if (StringUtils.isNoneNullString(list.get(position).getPayment().getPayWeek()) && !(list.get(position).getPayment().getPayWeek().equals("0"))) {
						String zh = toChinese(list.get(position).getPayment().getPayWeek());
						times.add("每周" + zh + "付");
					}
					if (StringUtils.isNoneNullString(list.get(position).getPayment().getPayOrderFlag())) {
						if (list.get(position).getPayment().getPayOrderFlag().equals("1")) {
							times.add("下单付");
						}
					}
					if (StringUtils.isNoneNullString(list.get(position).getPayment().getAccountAlipay())) {
						payways.add("支付宝");
					}
					if (StringUtils.isNoneNullString(list.get(position).getPayment().getAccountBankCardCode())) {
						payways.add("银行卡");
					}
					if (StringUtils.isNoneNullString(list.get(position).getPayment().getAccountWechat())) {
						payways.add("微信付");
					}
					if (StringUtils.isNoneNullString(list.get(position).getPayment().getPayOfflineFlag())) {
						if (list.get(position).getPayment().getPayOfflineFlag().equals("1")) {
							payways.add("线下付");
						}
					}
					shwoPopupWindow(view, position);

				}
				return true;
			}
		});
	}

	private void shwoPopupWindow(View view, final int position) {
		//用来存放当前的item的坐标值，第一个是x的坐标，第二个是y的坐标
		int[] location = new int[2];
		//把当前的item的坐标放到int数组里面
		view.getLocationInWindow(location);
		View popupView = View.inflate(mActivity, R.layout.order_detail_item_popupwindow_layout, null);
		//new 一个PopupWindow出来
		popupWindow = new PopupWindow(popupView, view.getWidth(), view.getHeight() - 20);
		//一定要给popupWindow设置一个背景图片，不然的话，会有很多未知的问题的
		//如没办法给它加上动画，还有显示会有问题等。
		//如果我们没有要设置的图片，那么我们就给它加上一个透明的背景图片
		Drawable drawable = new ColorDrawable(Color.TRANSPARENT);
		LinearLayout mChangeTimeLayout = (LinearLayout) popupView.findViewById(R.id.change_time_layout);
		LinearLayout mChangePayLayout = (LinearLayout) popupView.findViewById(R.id.change_pay_layout);
		LinearLayout mDeleteLayout = (LinearLayout) popupView.findViewById(R.id.delete_layout);
		mChangeTimeLayout.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (times.size() > 0) {
					new ChoosePickerDialog.Builder(mActivity).setTitle("选择付款方式").setData(times).setOnDataSelectedListener(new ChoosePickerDialog.OnSelectedListener() {
						@Override
						public void onSelected(String s, int i) {
							String payType;
							String payValue = null;
							if (s.contains("周")) {
								 payType = "week";
								 payValue = list.get(position).getPayment().getPayWeek();
							} else if (s.contains("月")) {
								 payType = "month";
								 payValue = list.get(position).getPayment().getPayMonth();
							} else {
								 payType = "orderPay";
							}
							Map<String, Object> map = new HashMap<>();
							map.put("fuction", "payType");
							if (StringUtils.isNoneNullString(payType)) {
								map.put("payType", payType);
							}
							if (StringUtils.isNoneNullString(payValue)) {
								map.put("payTypeValue", payValue);
							}
							map.put("cartItemUkid", list.get(position).getCartItemUkid());
							map.put("demandId", mDemanId);
							map.put("supplierBusinessId", supplierBusinessId);
							httpPost(ContractConstant.UPDATE_CART_ITEM_METHOD , map , 1 , true , "正在加载中...");

						}

						@Override
						public void onCancel() {

						}
					}).create().show();
				}
				popupWindow.dismiss();
			}
		});
		mChangePayLayout.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (payways.size() > 0) {
					new ChoosePickerDialog.Builder(mActivity).setTitle("选择付款渠道").setData(payways).setOnDataSelectedListener(new ChoosePickerDialog.OnSelectedListener() {
						@Override
						public void onSelected(String s, int i) {
							Map<String, Object> map = new HashMap<>();
							map.put("cartItemUkid", list.get(position).getCartItemUkid());
							map.put("demandId", mDemanId);
							map.put("supplierBusinessId", supplierBusinessId);
							map.put("fuction", "payWay");
							String payWay = null;
							if (s.equals("支付宝")) {
								payWay = "aliPay";
							} else if (s.equals("银行卡")) {
								payWay = "bank";
							} else if (s.equals("微信付")) {
								payWay = "wechatPay";
							} else if (s.equals("线下付")) {
								payWay = "offline";
							}
							map.put("payWay", payWay);
							httpPost(ContractConstant.UPDATE_CART_ITEM_METHOD , map , 2 , true , "正在加载中...");


						}

						@Override
						public void onCancel() {

						}
					}).create().show();
				}
				popupWindow.dismiss();

			}
		});
		mDeleteLayout.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Map<String, Object> map = new HashMap<>();
				map.put("cartItemUkid", list.get(position).getCartItemUkid());
				map.put("demandId", mDemanId);
				map.put("supplierBusinessId", supplierBusinessId);
				map.put("fuction", "delete");
				httpPost(ContractConstant.UPDATE_CART_ITEM_METHOD , map , 3 , true , "正在加载中...");
				popupWindow.dismiss();

			}
		});
		popupWindow.setBackgroundDrawable(drawable);
		popupWindow.setOutsideTouchable(true);
		int x = location[0];
		int y = location[1];
		//把popupWindow显示出来
		popupWindow.showAtLocation(view, Gravity.LEFT | Gravity.TOP, x, y);
	}


	@Override
	public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) {
		return null;
	}

	private void setData(final List<OrderDetailListBean.OrderDetailBean> mList) {
		ViewTreeObserver observer = myListView.getViewTreeObserver();
		observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
			public boolean onPreDraw() {
				if (!isMeasured) {
					isMeasured = true;
					if (orderDetailAdapter == null && isAdded() && null != mList) {
						orderDetailAdapter = new OrderDetailAdapter(mList, mActivity, myListView.getMeasuredHeight());
						myListView.setAdapter(orderDetailAdapter);
						orderDetailAdapter.setOnMoreClickListener(new OrderDetailAdapter.onMoreClickListener() {
							@Override
							public void onMore(View view, int position) {
								EventBus.getDefault().post(new OrderDetailOnItemClickEvent());
								times.clear();
								payways.clear();
								if (list.size() > 0 && list.get(position).getPayment() != null) {
									if (StringUtils.isNoneNullString(list.get(position).getPayment().getPayMonth()) && !(list.get(position).getPayment().getPayMonth().equals("0"))) {
										times.add("每月" +list.get(position).getPayment().getPayMonth() + "日付");
									}
									if (StringUtils.isNoneNullString(list.get(position).getPayment().getPayWeek()) && !(list.get(position).getPayment().getPayWeek().equals("0"))) {
										String zh = toChinese(list.get(position).getPayment().getPayWeek());
										times.add("每周" + zh + "付");
									}
									if (StringUtils.isNoneNullString(list.get(position).getPayment().getPayOrderFlag())) {
										if (list.get(position).getPayment().getPayOrderFlag().equals("1")) {
											times.add("下单付");
										}
									}
									if (StringUtils.isNoneNullString(list.get(position).getPayment().getAccountAlipay())) {
										payways.add("支付宝");
									}
									if (StringUtils.isNoneNullString(list.get(position).getPayment().getAccountBankCardCode())) {
										payways.add("银行卡");
									}
									if (StringUtils.isNoneNullString(list.get(position).getPayment().getAccountWechat())) {
										payways.add("微信付");
									}
									if (StringUtils.isNoneNullString(list.get(position).getPayment().getPayOfflineFlag())) {
										if (list.get(position).getPayment().getPayOfflineFlag().equals("1")) {
											payways.add("线下付");
										}
									}
									shwoPopupWindow(view, position);

								}

							}

							@Override
							public void onEditCount(View view ,int position) {
								//修改数量
								ShoppingCarQtyEvent shoppingCarQtyEvent = new ShoppingCarQtyEvent();
								shoppingCarQtyEvent.setCartItemUkid(mList.get(position).getCartItemUkid());
								shoppingCarQtyEvent.setDemandId(mDemanId);
								shoppingCarQtyEvent.setSupplierBusinessId(supplierBusinessId);
								shoppingCarQtyEvent.setFuction("qty");
								shoppingCarQtyEvent.setKuCunCount(mList.get(position).getInventoryQty());
								EventBus.getDefault().post(shoppingCarQtyEvent);
							}

							@Override
							public void onNameClick(View view, int position) {
								//跳转到商品详情页面
								PlaceOrdersGoodsDeatilsFragment fragment = new PlaceOrdersGoodsDeatilsFragment();
								PlaceOrdersBrowseGoodsBean.ItemListBean dataBean = new PlaceOrdersBrowseGoodsBean.ItemListBean();
								if (StringUtils.isNoneNullString(mList.get(position).getItemPublishUkid())) {
									dataBean.setItemPublishUkid(Long.valueOf(mList.get(position).getItemPublishUkid()));
								}
								Bundle bundle = new Bundle();
								bundle.putParcelable("data", dataBean);
								bundle.putString("demandId" , mDemanId);
								bundle.putInt("shppingNum" ,shoppingNum );
								fragment.setArguments(bundle);
								pushFragment(fragment);
							}
						});
					}
				}
				return true;
			}
		});


	}

	@Override
	public void setTitle() {

	}

	@Override
	public void requestDatas() {

	}

	@Override
	public void onSuccess(CommonClass commonClass, int what) {
		if (what == 1 || what == 2 ) {
			if (commonClass.getCode().equals("0")) {
				ShopingCarTotalPriceBean bean = JSON.parseObject(commonClass.getData().toString(), ShopingCarTotalPriceBean.class);
				EventBus.getDefault().post(new RefreshShoppCardEvent("refresh", bean.getTotalPrice()));
			} else {
				toast(commonClass.getMsg());
			}
		} else if (what == 3) {
			if (commonClass.getCode().equals("0")) {
				ShopingCarTotalPriceBean bean = JSON.parseObject(commonClass.getData().toString(), ShopingCarTotalPriceBean.class);
				EventBus.getDefault().post(new RefreshShoppCardEvent("refresh" , bean.getTotalPrice()));
				Intent intent = new Intent("refreshOrdersList");
				intent.putExtra("shopNum", bean.getTotalCount());
				mActivity.sendBroadcast(intent);
			} else {
				toast(commonClass.getMsg());
			}
		} else if (what == 4) {
			if (commonClass.getCode().equals("0")) {
				OrderDetailListBean orderDetailListBean = JSON.parseObject(commonClass.getData().toString(), OrderDetailListBean.class);
				if (orderDetailListBean != null && orderDetailListBean.getList() != null) {
					list = orderDetailListBean.getList();
					setData(orderDetailListBean.getList());
				}

			}
		} {

		}

	}

	@Override
	protected void loadDatas() {
		if (getArguments() != null && getArguments().getSerializable(ContractConstant.KEY_BUNDLE_VIEW_PAGER_DATA) != null) {
			final OrderDetailListBean listBean = (OrderDetailListBean) getArguments().getSerializable(ContractConstant.KEY_BUNDLE_VIEW_PAGER_DATA);
			int position = getArguments().getInt(ContractConstant.KEY_BUNDLE_POSITION);
			int pageNum = getArguments().getInt(ContractConstant.KEY_BUNDLE_PAGENUM);
			shoppingNum = Integer.valueOf(listBean.getTotal());
			if (StringUtils.isNoneNullString(listBean.getDemanId())) {
				mDemanId = listBean.getDemanId();
			}
			if (listBean != null) {
				if (StringUtils.isNoneNullString(listBean.getLogo())) {
					ImageloaderUtils.displayRoundImg(listBean.getLogo() , mLogoIv);
				}
				if (StringUtils.isNoneNullString(listBean.getTotalPrice())) {
					mTotalPriceTv.setText(StringUtils.getResourceStr(mActivity, R.string.place_orders_total_price, listBean.getTotalPrice()));
				}
				if (StringUtils.isNoneNullString(listBean.getName())) {
					mNameTv.setText(listBean.getName());
				}
				if (StringUtils.isNoneNullString(listBean.getSupplierBusinessId())) {
					supplierBusinessId = listBean.getSupplierBusinessId();
				}
			}
			list.clear();

			if (listBean.getList() != null && position == 0) {
				list = listBean.getList();
				setData(listBean.getList());
			} else {
				Map<String, Object> map = new HashMap<>();
				map.put("demandId", mDemanId);
				map.put("supplierBusinessId", supplierBusinessId);
				map.put("page", position + 1);
				map.put("size", 4);
				httpPost(ContractConstant.SHOPPING_CART_DETAIL_LIST, map, 4 , false , "");
			}


//
		}
	}

	@Override
	public void onReLoad(int code) {

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (popupWindow != null && popupWindow.isShowing()) {
			popupWindow.dismiss();
		}
	}

	private String toChinese(String string) {
		String[] s1 = { "零", "一", "二", "三", "四", "五", "六", "日", "八", "九" };
		String[] s2 = { "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千" };

		String result = "";

		int n = string.length();
		for (int i = 0; i < n; i++) {

			int num = string.charAt(i) - '0';

			if (i != n - 1 && num != 0) {
				result += s1[num] + s2[n - 2 - i];
			} else {
				result += s1[num];
			}
			System.out.println("  "+result);
		}

		System.out.println("----------------");
		System.out.println(result);
		return result;

	}
}
